<template>
  <div v-if="itemShow">
    <el-form :disabled="disabled">
      <el-row
        v-for="(item, index) in items"
        :key="index"
        align="middle"
        type="flex"
        style="background-color:#f5f7fa;padding:10px;border-radius:5px;margin-bottom:10px;"
      >
        {{ index + 1 }}
        <el-col :span="disabled?24:20">
          <el-input
            v-model="item.value"
            :placeholder="placeholder"
            :disabled="item.disabled"
            @change="val => onChange(index, val)"
          />
        </el-col>
        <el-col :span="2" :pull="1" :push="1" :style="{ display: disabled ? 'none' : 'block' }">
          <i
            v-if="addShow(index)"
            class="el-icon-circle-plus-outline"
            style="font-size:28px;cursor:pointer;"
            @click="addItem(index + 1)"
          />
          <i
            v-if="removeShow(item, index)"
            class="el-icon-remove-outline"
            style="font-size:28px;cursor:pointer;color:#606266;"
            @click="removeItem(index)"
          />
        </el-col>
      </el-row>
    </el-form>
  </div>
  <div v-else :style="{ display: disabled ? 'none' : 'block' }">
    <i
      class="el-icon-circle-plus-outline"
      style="font-size:28px;vertical-align:middle;color:#606266;cursor:pointer;"
      @click="addItem(0)"
    />
  </div>
</template>

<script>
export default {
  name: 'PktMultiInput',
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    min: {
      type: Number,
      default: 0
    },
    max: {
      type: Number,
      default: 999
    },
    defaults: {
      type: Array,
      default: () => []
    },
    placeholder: {
      type: String,
      default: ''
    },
    onChange: {
      type: Function,
      default: () => {}
    }
  },
  data: function() {
    return {
      items: []
    }
  },
  computed: {
    itemShow() {
      return this.items.length !== 0
    }
  },
  created: function() {
    const length = this.defaults.length
    for (let i = length - 1; i >= 0; i--) {
      this.addItem(i, this.defaults[i])
    }
  },
  methods: {
    addShow(index) {
      const length = this.items.length
      return index === length - 1 && this.max !== 0 && length < this.max
    },
    removeShow(item, index) {
      const length = this.items.length
      return (
        !item.disabled &&
        (this.min === 0 ||
          length > this.min ||
          (this.max !== 0 && index === length - 1 && length === this.max))
      )
    },
    addItem(index, item) {
      if (item) {
        this.items.unshift(item) // 添加到开头
      } else {
        this.items.unshift({}) // 添加到开头
      }
      this.$emit('add', index, item)
    },
    removeItem(index) {
      this.items.splice(index, 1)
      this.$emit('remove', index)
    }
  }
}
</script>
